const mongoose = require('mongoose');

const User= require('../model/user.model');

//zeng
exports.create = function (req,res,next){
    const user = new User(req.body);//实例化对象，req.body代表是post的数据提交，参数从body中获取
    user.save().then(data=>{
        res.json(data);//进行数据保存，保存后数据以json格式进行输出。
    })
}

//shan
exports.remove = function(req,res,next){
    var id = req.params.id;
    User.findByIdAndRemove(id,function(err,data){
        res.json({message:'success done'});
    })
}
//gai
exports.update = function(req,res,next){
    const id = req.params.id;
    User.findByIdAndUpdate(id,{$set:req.body},{new:false}).then(user=>{
        res.json(user);
    })
}
//cha
exports.list = function(req,res,next){
    var page = req.body.page ? req.body.page : 1;
    var rows = req.body.rows ? req.body.rows : 5;
    var queryCondition = {};

    if(req.body.name && req.body.name.trim().length > 0){
        name = req.body.name;
        queryCondition = {
            name : new RegExp(name ,'i')
        }
    }
    User.paginate(queryCondition,{page:+page,limit:+rows},function(err,result){
        result.rows = result.docs;
		delete result.docs;
        res.json(result); 
    })
}